package com.gu.lock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 使用lock实现多线程卖票
 *
 * @author gusongliao
 * @date 2023-05-18 17:22
 */
public class LSaleTicket {

    public static void main(String[] args) {
        // 创建Ticket对象
        LTicket ticket = new LTicket();

        // 创建三个线程
        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                ticket.sale();
            }
        }, "AA").start();

        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                ticket.sale();
            }
        }, "BB").start();

        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                ticket.sale();
            }
        }, "CC").start();
        System.out.println("------------------");

    }

}

class LTicket {
    private int number = 30;

    //创建可重入锁
    private final ReentrantLock lock = new ReentrantLock();

    public void sale() {

        try {
            // 上锁
            lock.lock();

            if (number > 0) {
                System.out.println(Thread.currentThread().getName() + "：卖出：" + (number--) + "：剩余：" + (number)) ;
            }

        } finally {
            //解锁
            lock.unlock();
        }

    }
}
